package com.quark.framework.base;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import com.quark.framework.utility.QuarkLog;

public class QuarkPojoBase {
	private Map<String, Field> fieldBuf = new HashMap<String, Field>();
	
	public QuarkPojoBase()
	{
		Field[] fields = this.getClass().getFields(); 		
		for(int i = 0; i < fields.length; i++)
		{
			fields[i].setAccessible(true);
			fieldBuf.put(fields[i].getName(), fields[i]);
		}
	}
	public boolean setValue(String name, Object value)
	{
		if(hasMember(name))
		{
			Field field = getMember(name);
			try
			{
				field.set(this, value);
			}
			catch(Exception e)
			{
				QuarkLog.logError("ReflectionBase set value failed," + field.getType().getName() + " != " + value.getClass().getName());
			}
			return true;
		}
		else
		{
			QuarkLog.logError("ReflectionBase no such field:" + name);
			return false;
		}
	}
	
	public Object getMemberValue(String name)
	{
		Field field = getMember(name);
		if(field != null)
		{
			Object retObj = null;
			try
			{
				retObj = field.get(this);
			}
			catch(Exception e)
			{
				QuarkLog.log(e);
			}
			return retObj;
		}
		else
		{
			QuarkLog.logError("ReflectionBase, get value failed, not such field:"+name);
			return null;
		}
		
	}
	
	public boolean hasMember(String name)
	{
		String[] members = getMemberNames();
		for(String memberName : members)
		{
			if(memberName == name)
			{
				return true;
			}
		}
		return false;
	}
	
//	public boolean init(Object param);
	public Field getMember(String name)
	{
		Field f = fieldBuf.get(name);
		if(f == null)
			return null;
		return f;
	}
	public Class<?>[] getMemberTypes()
	{
		Iterator<Field> it = fieldBuf.values().iterator();
		Class<?>[] types = new Class[fieldBuf.values().size()];
		for(int i = 0; it.hasNext(); i++)
		{
			types[i] = it.next().getType();
		}
		return types; 
	}
	
	public String[] getMemberNames()
	{
		Iterator<String> it = fieldBuf.keySet().iterator();
		String[] names = new String[fieldBuf.values().size()];
		for(int i = 0; it.hasNext(); i++)
		{
			names[i] = it.next();
		}
		return names;
	}

}
